package com.cqndt.disaster.device.parsing;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.cqndt.disaster.device.common.util.GetRequestJsonUtils;
import com.cqndt.disaster.device.common.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Frog
 */
@RestController
@RequestMapping(value = "rain")
@Slf4j
public class RainAccess {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static Map<String, String> keys = new HashMap<>(16);

    @PostMapping(value = "auth")
    public Result auth(String account, String password) {
        Result result = new Result();
        String key = String.valueOf(Math.abs((account + password).hashCode()));
        keys.put("key", key);
        result.setMsg(key);
        return result;
    }

    @PostMapping(value = "upload")
    public Result upload(HttpServletRequest request) {
//        String key = request.getHeader("key");
//        if (null != key && keys.get("key") != null) {
//            if (key.endsWith(keys.get("key"))) {
        String requestJsonString = null;
        try {
            requestJsonString = GetRequestJsonUtils.getRequestJsonString(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Map<String, Object>> mapList = (List<Map<String, Object>>) JSONArray.parse(requestJsonString);

        List<Map<String, Object>> tempMapList = new ArrayList<>();
        for(Map<String, Object> map : mapList){
            Map<String, Object> tempMap = new HashMap<>();
            tempMap.put("number", map.get("sensor_no"));
            tempMap.put("value", map.get("value"));
            tempMap.put("acqTime", map.get("time"));
            tempMap.put("type", 10);
            tempMapList.add(tempMap);
        }

//                for (Map<String, Object> stringObjectMap : mapList) {
//                    stringObjectMap.put("type", "10");
//                }
        String s = JSON.toJSONString(tempMapList);
        net.sf.json.JSONArray data = net.sf.json.JSONArray.fromObject(s);
        byte[] serialize = SerializationUtils.serialize(data);
        log.info("雨量接收数据：" + mapList);
        rabbitTemplate.convertAndSend("yunnan.done.data", serialize);
        return new Result().success();
//            }
//        }
//        return new Result().failure(1, "错误的鉴权");
    }


}
